from typing import List, Optional
from fastapi import APIRouter, status, Body
from fastapi.param_functions import Query
from fastapi.requests import Request
from blog.models import Comment, Comment_Py, CommentIn_Py, CommentRoot_Py
from fastapi.responses import JSONResponse
from tortoise.contrib.fastapi import HTTPNotFoundError
from tortoise import exceptions
from tortoise.query_utils import Q
from fastapi_pagination import Page, paginate


router = APIRouter(prefix="/comments", tags=["comment"])

@router.post("/", response_model=Comment_Py)
async def create_comment(comment: CommentIn_Py, request: Request):
    if not request.user.is_authenticated:
        return JSONResponse(content={"error":"游客不能发表评论"}, status_code=status.HTTP_400_BAD_REQUEST)
    data = comment.dict(exclude_unset=True)
    if request.user.is_authenticated:
        data.update({"owner":"admin"})
    else:
        if data["owner"] == "admin":
            return JSONResponse(content={"error": "invalid name"}, status_code=status.HTTP_400_BAD_REQUEST)
    try:
        comment_obj = await Comment.create(**data)
    except exceptions.ValidationError as e:
        return JSONResponse(content={"error":e.args[0]}, status_code=status.HTTP_400_BAD_REQUEST)
    return await Comment_Py.from_tortoise_orm(comment_obj)

# 所有的comments 只有管理员可以访问，方便管理数据
@router.get("/", response_model=Page[Comment_Py])
async def get_comments(request:Request):
    if not request.user.is_authenticated:
        return JSONResponse(status_code=status.HTTP_403_FORBIDDEN)
    qs = Comment.all()
    comments = await Comment_Py.from_queryset(qs)
    return paginate(comments)

# 只用于展示数据，需要提供文章id
@router.get("/roots/", response_model=Page[Comment_Py])
async def get_root_comments(article_id:int, topic_id:Optional[int]=Query(None)):
    qs = Comment.filter(article_id=article_id)
    if topic_id:
        qs = qs.filter(Q(topic_id=topic_id) | Q(id=topic_id))
    comments =  await Comment_Py.from_queryset(qs)
    return paginate(comments)

@router.get("/{id}/replies/", response_model=Page[Comment_Py])
async def get_replies(id: int):
    comments =  await Comment_Py.from_queryset(Comment.filter(parent=id))
    return paginate(comments)

@router.get("/{id}/", response_model=Comment_Py)
async def get_comment_by_id(id:int):
    try:
        return await Comment_Py.from_queryset_single(Comment.get(id=id))
    except exceptions.DoesNotExist:
        return JSONResponse(content={"error":"not found"}, status_code=status.HTTP_404_NOT_FOUND)

@router.delete("/{id}/")
async def delete_comment(id: int):
    await Comment.get(id=id).update(is_deleted=True, content="已删除")